
import java.io.FileReader;
import java.util.HashMap;

import java_cup.runtime.Scanner;
import typage.Typing;
import ast.JmmFile;
import errors.TypingError;



class Main {

    static boolean parse_only = false, type_only = false;
    
    static void report(String filename, int line, int character) {
	System.out.println("File \"" + filename + "\"" +
			   ", line " + line +
			   ", character " + character + ":");
    }

    static void usage() {
	System.out.println
	    ("usage: compilo [-parse-only] [-type-only] file.jmm");
	System.exit(1);
    }
    
    public static void main(String arg[]) {
	String filename = null;
	
	for (int i = 0; i < arg.length; i++) {
	    String a = arg[i];
	    if (a.equals("-parse-only")) 
		parse_only = true;
	    else if (a.equals("-type-only")) 
		type_only = true;
	    else {
		if (filename != null) usage();
		filename = a;
	    }
	}

	if ( filename==null || !filename.endsWith(".jmm"))usage();
	
	try {
	    Scanner lex = new Lexer(new FileReader(filename));
	    parser p = new myparser(lex, filename);
	    JmmFile ast = (JmmFile)p.parse().value;
	    if (parse_only) System.exit(0);
	    HashMap<String,Integer> t = Typing.file(ast);
	    if (type_only) System.exit(0);
	    
        String vm_file = filename.substring(0,filename.length()-4) + ".vm";
        (new Compile(vm_file , t )).visit(ast);
        System.out.println("fini  :)");
	}
	catch (TypingError e) {
	    if (e.loc != null) 
		report(filename, e.loc.loc_line, e.loc.loc_char);
	    System.out.println("typing error: " + e.msg);
	    System.exit(1);
	}
	catch (Exception e) {
	    System.out.println("error: " + e);
	    e.printStackTrace();
	    System.exit(2);
	}
    }
}
